import { useEffect, useState } from 'react';

import axios from 'axios';

const TOKEN_NAME = 'HKZF_CITY';

type CityInfo = {
  label: string;
  value: string;
};

export const getCurrentCity = (): Promise<CityInfo> => {
  const localCity = localStorage.getItem(TOKEN_NAME);
  // 如果不存在 调用百度api获取一下
  if (!Boolean(localCity)) {
    return new Promise((resolve, reject) => {
      // 本地储存中不存在城市信息时通过定位获取
      const currentCity = new BMapGL.LocalCity();

      currentCity.get(async (res) => {
        try {
          const result = await axios.get(
            `http://localhost:8080/area/info?name=${res.name}`
          );
          localStorage.setItem(TOKEN_NAME, JSON.stringify(result.data.body));
          resolve(result.data.body);
        } catch (error) {
          reject(error);
        }
      });
    });
  } else {
    return Promise.resolve(JSON.parse(localCity));
  }
};

export const useCity = () => {
  // 设置当前城市名称和id的state
  const [value, setValue] = useState<string>('');
  const [label, setLabel] = useState<string>('');

  // 挂载时获取当前城市
  useEffect(() => {
    const getCity = async () => {
      const result = await getCurrentCity();

      setValue(result.value);

      setLabel(result.label);
    };

    getCity();
  }, []);

  return [value, label];
};

// 如果当前页面调用getCity但是token丢失，会直接报错，不建议使用
export const getCity = () => JSON.parse(localStorage.getItem(TOKEN_NAME));

export const setCity = (value) => localStorage.setItem(TOKEN_NAME, value);
